package com.starsoft.frame.util;

import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.starsoft.frame.base.service.PreferenceService;

@Component
public class EmailService {

	private static Logger logger = LoggerFactory.getLogger(EmailService.class);
	
	@Autowired
	PreferenceService preferenceService;
	
	public boolean sendEmail(String emailTo, String subject, String content) {
		try {
			
			String systemEmailAdress = preferenceService.getPreference("systemEmailAdress");
			String systemEmailPassword = preferenceService.getPreference("systemEmailPassword");
			
			Properties props = new Properties();
			props.setProperty("mail.host", "smtp.163.com");
			props.setProperty("mail.smtp.auth", "true");
			props.setProperty("mail.transport.protocol", "smtp");
			props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");  
	        props.setProperty("mail.smtp.socketFactory.fallback", "false");  
	        props.setProperty("mail.smtp.port", "465");  
	        props.setProperty("mail.smtp.socketFactory.port", "465");
			Session session = Session.getInstance(props);

			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(systemEmailAdress));
			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo));  
			msg.setSubject(subject);

            Multipart mainPart = new MimeMultipart();  
            MimeBodyPart messageBodyPart = new MimeBodyPart(); 
            messageBodyPart.setContent(content,"text/html; charset=utf-8");  
            mainPart.addBodyPart(messageBodyPart);  
            msg.setContent(mainPart);
            
			Transport.send(msg, systemEmailAdress, systemEmailPassword);
			logger.info(emailTo+" "+subject+" "+content);
			return true;
		} catch (Exception e) {
			logger.error("发送邮件失败," + emailTo + subject, e);
			return false;
		}
	}

}
